<?php

// TODO layui 返回值公共方法

/**
 * pear 列表返回值格式
 */

use App\Services\client\PlatformService;

if (! function_exists('pearListAjaxReturn')) {
    function pearListAjaxReturn($data)
    {
        $data = [
            'code' => 200,
            'msg' => '正在请求中...',
            'count' => $data->total(),
            'data' => $data->items(),
        ];

        return $data;
    }
}

/**
 * pear 列表返回值格式
 */
if (! function_exists('pearListReturn')) {
    function pearListReturn($data)
    {
        $data = [
            'code' => 200,
            'msg' => '正在请求中...',
            'data' => $data,
        ];

        return $data;
    }
}

/**
 * pear 树形表格 列表返回值格式
 */
if (! function_exists('pearTreeAjaxReturn')) {
    function pearTreeAjaxReturn($data)
    {
        $data = [
            'code' => 200,
            'msg' => '正在请求中...',
            'count' => count($data),
            'data' => $data,
        ];

        return $data;
    }
}

// TODO 公共方法

/**
 * 总后台基础变量
 *
 * @return array
 */
if (! function_exists('baseVar')) {
    function baseVar(): array
    {
        $adminConfig = config('amis');

        return [
            'cookie_prefix' => '',
            'request_path' => request()->path(),
            'admin' => $adminConfig,
        ];

    }
}

/**
 * 生成唯一的订单编号
 *
 * @Desc: 将用户ID、时间戳和随机数组合成订单编号
 *
 * @param $userId
 * @param $platform
 * @return string
 *
 * @author: zhx
 *
 * @Time: 2023/8/11 10:41
 */
if (! function_exists('generateOrderNumber')) {
    function generateOrderNumber($userId, $platform)
    {
        $timestamp = time();
        $randomNumber = mt_rand(1000, 9999); // 生成一个随机数
        // 将用户ID、时间戳和随机数组合成订单编号
        $orderNumber = sprintf('%s-%s-%s-%s', $timestamp, $userId, $platform, $randomNumber);

        return $orderNumber;
    }
}

/**
 * 根据生日计算年龄
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:42
 *
 * @Interface howOld
 *
 * @param $birth
 * @return int|string
 */
if (! function_exists('howOld')) {
    function howOld($birth)
    {
        [$birthYear, $birthMonth, $birthDay] = explode('-', $birth);
        [$currentYear, $currentMonth, $currentDay] = explode('-', date('Y-m-d'));
        $age = $currentYear - $birthYear - 1;
        if ($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay) {
            $age++;
        }

        return $age;
    }
}

/**
 * 生成的二维码数据
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:16
 *
 * @Interface generateQRCode
 *
 * @param $data  要生成的二维码数据
 * @param $filename 生成的二维码图片文件名和路径
 * @param $size
 */
if (! function_exists('generateQRCode')) {
    function generateQRCode($data, $filename, $size = 200)
    {
        // 创建 QrCode 对象
        $qrCode = new \Endroid\QrCode\QrCode($data);

        // 设置二维码图片大小
        $qrCode->setSize($size);

        // 保存生成的二维码图片
        $qrCode->writeFile($filename);
    }
}

/**
 * 将手机号中间4位替换为*
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:21
 *
 * @Interface suohao
 *
 * @param $phone
 * @return string
 */
if (! function_exists('suohao')) {
    function suohao($phone)
    {
        $p = substr($phone, 0, 3).'****'.substr($phone, 7, 4);

        return $p;
    }
}

/**
 * 字符串超出长度出按...显示
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:38
 *
 * @Interface subtext
 *
 * @param $text
 * @param $length
 * @return mixed|string
 */
if (! function_exists('subtext')) {
    function subtext($text, $length)
    {
        if (mb_strlen($text, 'utf8') > $length) {
            return mb_substr($text, 0, $length, 'utf8').' …';
        }

        return $text;
    }
}

/**
 * object2array class转换数组
 *
 * @return   [array]                [成功true, 失败 错误信息]
 */
if (! function_exists('object2array')) {
    function object2array(&$object)
    {
        $object = json_decode(json_encode($object), true);

        return $object;
    }
}

/**
 * 获取IP
 */
if (! function_exists('getClientIpLyh')) {
    function getClientIpLyh()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        if (getenv('HTTP_X_REAL_IP')) {
            $ip = getenv('HTTP_X_REAL_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
            $ips = explode(',', $ip);
            $ip = $ips[0];
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = '0.0.0.0';
        }

        return $ip;
    }
}

/**
 * 处理导出数据时候空数据转换成字符串
 */
if (! function_exists('hadle_exscel_null_data')) {
    function hadle_exscel_null_data($row_arr, $key = [])
    {
        $rows_arr_new = [];
        $rows_arr_temp = 0;
        if (! empty($key)) {
            foreach ($key as $k1 => $v1) {
                if (isset($row_arr[$k1])) {
                    $value = $row_arr[$k1];
                    $rows_arr_new[$rows_arr_temp] = strval($value);
                    $rows_arr_temp++;
                } else {
                    $rows_arr_new[$rows_arr_temp] = '';
                    $rows_arr_temp++;
                }
            }
        } else {
            foreach ($row_arr as $k => $v) {
                if ($v != null) {
                    $rows_arr_new[$rows_arr_temp] = strval($v);
                    $rows_arr_temp++;
                }
            }
        }
        $row_arr = $rows_arr_new;

        return $row_arr;
    }
}

/**
 * 导出EXECL表格
 */
if (! function_exists('export_excel')) {
    function export_excel($excel_keys, $data_keys, $datas, $count)
    {
        // 文件名和文件类型
        $fileNameArr = [];
        if ($count == 0) {
            echo '没有可以导出的数据';
            exit();
        }
        $for_count = (ceil($count / 10000)); //10000
        for ($a = 1; $a <= $for_count; $a++) {
            //生成临时文件
            // 创建Excel文件对象
            $objPHPExcel = new PHPExcel();
            //根据excel坐标，添加数据
            $objPHPExcel->setActiveSheetIndex(0);
            $cellName = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'];
            $setActiveSheetIndex = $objPHPExcel->setActiveSheetIndex(0);
            foreach ($excel_keys as $k_1 => $v_1) {

                $setActiveSheetIndex->setCellValue($cellName[$k_1].'1', $v_1);
            }
            //插入表格数据
            $i = 2;
            $limit = 10000; //10000
            $page = ($a - 1) * $limit;
            //导入数据如果处理呢
            //        if($a == 2){
            //            dd($data);
            //        }
            $data = page_array($limit, $a, $datas, 0);

            foreach ($data as $key => $value) {
                foreach ($data_keys as $key_data => $value_data) {
                    $setActiveSheetIndex->setCellValue($cellName[$key_data].$i, $data[$key][$value_data]."\t");
                }
                $i++;
            }
            // 设置第一个sheet为工作的sheet
            $objPHPExcel->setActiveSheetIndex(0);

            //保存Excel 95格式文件，，保存路径为当前路径，
            $filename = $a.time().'.xlsx';
            $filename = iconv('UTF-8', 'GBK//IGNORE', $filename);
            $fileNameArr[] = $filename;
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save($filename);
        }
        if ($for_count > 1) {
            //进行多个文件压缩
            $filename = time().'.zip';
            $zip = new \ZipArchive();
            $zip->open($filename, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
            //向压缩包中添加文件
            foreach ($fileNameArr as $file) {
                $zip->addFromString($file, file_get_contents($file)); //向压缩包中添加文件
            }

            $zip->close();  //关闭压缩包

            foreach ($fileNameArr as $file) {
                unlink($file); //删除csv临时文件
            }
        }
        //输出压缩文件提供下载
        header('Cache-Control: max-age=0');
        header('Content-Description: File Transfer');
        header('Content-disposition: attachment; filename='.$filename); // 文件名
        header('Content-Type: application/zip'); // zip格式的
        header('Content-Transfer-Encoding: binary'); //
        header('Content-Length: '.filesize($filename)); //
        ob_clean();
        flush();
        readfile($filename); //输出文件;
        unlink($filename); //删除压缩包临时文件
    }
}

// TODO 日期公共方法

/**
 * 获取日期对应的星期
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:33
 *
 * @Interface getWeek
 *
 * @param $date
 * @return string
 */
if (! function_exists('getWeek')) {

    function getWeek($date)
    {
        //强制转换日期格式
        $date_str = date('Y-m-d', strtotime($date));
        //封装成数组
        $arr = explode('-', $date_str);
        //参数赋值
        //年
        $year = $arr[0];
        //月，输出2位整型，不够2位右对齐
        $month = sprintf('%02d', $arr[1]);
        //日，输出2位整型，不够2位右对齐
        $day = sprintf('%02d', $arr[2]);
        //时分秒默认赋值为0；
        $hour = $minute = $second = 0;
        //转换成时间戳
        $strap = mktime($hour, $minute, $second, $month, $day, $year);
        //获取数字型星期几
        $number_wk = date('w', $strap);
        //自定义星期数组
        $weekArr = ['日', '一', '二', '三', '四', '五', '六'];

        //获取数字对应的星期
        return $weekArr[$number_wk];
    }
}

/**
 * 获取时间的开始到结束 年 月 日期  时间
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:34
 *
 * @Interface getMonthTimeToStr
 *
 * @param $yearMonth
 * @return array
 */
if (! function_exists('getMonthTimeToStr')) {
    function getMonthTimeToStr($yearMonth)
    {
        $startTime = $yearMonth.'-01';
        $endTime = date('Y-m-d', strtotime("$startTime +1 month -1 day"));

        return ['stime' => strtotime($startTime.' 00:00:00'), 'etime' => strtotime($endTime.' 23:59:59')];
    }
}

/**
 * 获取时间范围  昨天 今天  明天  上周  下周
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:36
 *
 * @Interface periodTime
 *
 * @return array
 */
if (! function_exists('periodTime')) {
    function periodTime()
    {
        $time = [];
        //php获取昨日起始时间戳和结束时间戳
        $time['firstDay'][] = $firstBeginDay = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')));
        $time['firstDay'][] = $firstEndDay = date('Y-m-d 23:59:59', mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1);
        //php获取今日开始时间戳和结束时间戳
        $time['Today'][] = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d'), date('Y')));
        $time['Today'][] = date('Y-m-d 23:59:59', mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1);
        //明天开始时间UNIX时间戳
        $time['lastday'][] = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')));
        $time['lastday'][] = date('Y-m-d 23:59:59', mktime(23, 59, 59, date('m'), date('d') + 1, date('Y')));
        //php获取上周起始时间戳和结束时间戳
        $time['firstWeek'][] = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y')));
        $time['firstWeek'][] = date('Y-m-d 23:59:59', mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y')));
        //php获取下周时间戳和结束时间戳
        $time['lastWeek'][] = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y')));
        $time['lastWeek'][] = date('Y-m-d 23:59:59', mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y')));

        return $time;
    }
}

/**
 * 删除文件夹及里面的文件
 *
 * @Notes:
 *
 * @Author: zhx
 *
 * @Date: 2023-07-18
 *
 * @Time: 16:37
 *
 * @Interface deleteDir
 *
 * @param $dir 传入文件夹的路径
 * @return false|void
 */
if (! function_exists('deleteDir')) {
    function deleteDir($dir)
    {
        if (! $handle = @opendir($dir)) {
            return false;
        }
        while (false !== ($file = readdir($handle))) {
            if ($file !== '.' && $file !== '..') {       //排除当前目录与父级目录
                $file = $dir.'/'.$file;
                if (is_dir($file)) {
                    deleteDir($file);
                } else {
                    @unlink($file);
                }
            }
        }
        @rmdir($dir);
    }
}

/**
 * php请求网络的方法
 *
 * @param $url
 * @param $httpCode
 * @return bool|string
 */
if (! function_exists('curl_get')) {

    function curl_get($url, &$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $file_contents;
    }
}

/**
 * php请求网络的方法
 *
 * @param $url
 * @param $httpCode
 * @return bool|string
 */
if (! function_exists('curl_post')) {
    function curl_post($url, $post_data)
    {
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $res = curl_exec($ch); //运行curl
        curl_close($ch);

        return $res;
    }
}

/**
 * 加密函数
 *
 * @Desc:
 *
 * @param $number
 * @param $uid
 * @return string
 *
 * @author: zhx
 *
 * @Time: 2023/9/25 14:38
 */
if (! function_exists('customEncrypt')) {
    function customEncrypt($number, $uid)
    {
        return $number.'$'.$uid;
    }
}

/**
 * 解密函数
 *
 * @Desc:
 *
 * @param $number
 * @param $uid
 * @return string
 *
 * @author: zhx
 *
 * @Time: 2023/9/25 14:38
 */
if (! function_exists('customDecrypt')) {
    function customDecrypt($data)
    {
        $arr = explode('$', $data);
        if (count($arr) != 2) {
            return false;
        }
        // 增加platform下platform_id
        $platformInfo = PlatformService::getinfoBynumber($arr[0]);
        $platformInfo->platform_id = $platformInfo->id;

        return [
            'platformNumber' => $arr[0],
            'userid' => $arr[1],
            'platform' => $platformInfo,
            'number' => $data,
            'loginType' => Request()->session()->get('loginType'),
        ];

        return $data;
    }
}

// TODO -----------------------------------
